package cn.itcast.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "PurchaseServlet", urlPatterns = "/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        if (id == null) {
            resp.sendRedirect("ListCakeServlet");
            return;
        }

        shop shop = shopDB.getCake(id);
        if (shop == null) {
            resp.sendRedirect("ListCakeServlet");
            return;
        }

        HttpSession session = req.getSession();
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        if (cart == null) {
            cart = new ArrayList<>();
            session.setAttribute("cart", cart);
        }

        // 检查购物车中是否已有此蛋糕，如果有则增加数量，否则添加新的 CartItem
        boolean found = false;
        for (CartItem item : cart) {
            if (item.getCake().getId().equals(shop.getId())) {
                item.setQuantity(item.getQuantity() + 1);
                found = true;
                break;
            }
        }
        if (!found) {
            CartItem newItem = new CartItem(shop, 1);
            cart.add(newItem);
        }

        resp.sendRedirect("CartServlet");
    }
}